<?php

include dirname(dirname(dirname(__FILE__))) . '/include/common.php';

class webServiceCronJobUpdateFriendList extends core {

    public function process($facebook_id,$access_token,$user_id) {
        $fql_query_url = 'https://graph.facebook.com/fql?q=SELECT%20uid,username,first_name,last_name,pic_square%20FROM%20user%20WHERE%20uid%20IN%20%28SELECT%20uid2%20FROM%20friend%20WHERE%20uid1%20=%20'.$facebook_id.'%29&access_token='.$access_token;
        $fql_query_result = file_get_contents($fql_query_url);
        $fql_query_obj = json_decode($fql_query_result, true);
       // $folder_photo = dirname(dirname(dirname(__FILE__))) . '/photo/';
        $friend_list = $fql_query_obj["data"];
        foreach ($friend_list as $friend) {
            $data = array();
            $data['firstname'] = $friend["first_name"];
            $data['lastname'] = $friend["last_name"];
            $data['email'] = '';
            $data['email_facebook'] = $friend["username"]."@facebook.com";
            $data['phone'] = '';
            $data['address'] = '';
            $data['city'] = '';
            $data['state'] = '';
            $data['zipcode'] = '';
            $data['user_id'] = $user_id;
            $data['fbid'] = $friend["uid"];
            $data['is_invite'] = 0;
            //save photo
//            $image_src = file_get_contents($friend["pic_square"]);          
//            $image_name_des = time() . rand(10000, 99999) . session_id() . '.jpg';
//            file_put_contents($folder_photo.$image_name_des,$image_src);
//            $data['photo'] = $image_name_des;
            $data['photo'] = $friend["pic_square"];
            
            /* If userEmail is NOT found in the database => return error code 4 */
            $fields = array();
            $values = array();
            $this->_preDataForInsert($data, $fields, $values);
            $fields = implode(',', $fields);
            $values = implode(',', $values);
            $this->db->query("INSERT INTO `guests` ({$fields}) VALUES ({$values});");
           
        }
         
        $this->_JSONResponse(array('error' => 0, 'msg' => 'Your Facebook friend list has been updated'));
    }

}
$facebook_id =$argv[1];
$access_token =$argv[2];
$user_id =$argv[3];
$processor = new webServiceCronJobUpdateFriendList();
$processor->process($facebook_id,$access_token,$user_id);
?>